﻿using System;
using System.IO;
using System.Data;
using System.Drawing;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using LEDDataBase;
using LEDHelper;
using System.Windows.Interop;
using System.Windows.Shapes;
namespace LEDManager
{
    /// <summary>
    /// Interaction logic for LED.xaml
    /// </summary>
    public partial class LEDUnit2 : Window
    {
        private HwndSource m_hwndSource;
        public IntPtr Hwnd;
        public ushort devType;
        public ushort comSpeed;
        public ushort comPort;
        public ushort comFlow;
        public ushort locPort;
        public ushort rmtPort;
        public ushort srcAddr;
        public ushort dstAddr;
        int SizeConst = 16;
        public String rmtHost
        {
            get
            {
                return RowLED["RMTHOST"].ToString();
            }
            set
            {
                RowLED["RMTHOTST"] = value;
            }
        }
        public uint txTimeo;   //发送后等待应答时间 ====超时时间应为txTimeo*txRepeat
        public uint txRepeat;  //失败重发次数
        public uint txMovewin; //划动窗口
        public uint key;       //通讯密钥
        public int pkpLength;  //数据包大小
        private const int WM_LED_NOTIFY = 1025;
        string BackGroundBmp = "NO";
        string progID = "";
        int screentyp = LEDAPI.SCREEN_COLOR;
        string fileroot;
        string filepath;
        string filestatus;
        LEDData m_data;
        int dev = -1;
        public DataRow RowLED;
        public DataRow dwLEDStatus;
        DataTable LEDStatus;
        DataSet setLED;
        public string ledkey = "";
        public string system = "000";
        public int ledid = 1;
        public Int32 baudrate = 0;
        Int32 param_index = 0;
        Int32 notifymode = 0;
        Int32 wmhandle = 0;
        Int32 wmmessage = 0;
        Int32 address = 255;
        int width = 128;
        int height = 32;
        public int nWidth
        {
            get
            {
                return width;
            }
            set
            {
                width = value;
            }
        }
        public int nHeight
        {
            get
            {
                return height;
            }
            set
            {
                height = value;
            }
        }
        DataRow dwProg, dwFont, dwClock, dwPicture, dwText, dwLeaf, dwLeafDetail;
        public LEDDataSet lEDDataSet
        {
            get
            {
                return (LEDDataSet)this.FindResource("lEDDataSet");
            }
        }
        CollectionViewSource vwLEDLIST
        {
            get
            {
                return (CollectionViewSource)this.FindResource("vwLEDLIST");
            }
        }
        CollectionViewSource vwMASTER
        {
            get
            {
                return (CollectionViewSource)this.FindResource("vwMASTER");
            }
        }
        CollectionViewSource vwLEDLOCATION
        {
            get
            {
                return (CollectionViewSource)this.FindResource("vwLEDLOCATION");
            }
        }
        public LEDUnit2()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(LEDUnit_Loaded);
            this.Unloaded += new RoutedEventHandler(LEDUnit_Unloaded);
        }

        void LEDUnit_Loaded(object sender, RoutedEventArgs e)
        {
            #region====Refresh LED================
            PerformCommand("LED_GetPower");
            #endregion
        }

        void LEDUnit_Unloaded(object sender, RoutedEventArgs e)
        {

        }
        ~LEDUnit2()
        {
            DumpStatusData();
        }
        TSenderParam sender = new TSenderParam();
        public void SetUp(DataRow dwLED)
        {
            try
            {
                RowLED = dwLED;
                fileroot = System.IO.Path.Combine(PathHelper.ApplicationPath, @"Data\LEDList");
                setLED = new DataSet();
                dwLEDStatus = null;
                LEDStatus = lEDDataSet.LEDSTATUS.Clone();

                m_data = new LEDData();
                DataSet setResult = new DataSet();
                m_data.Reset();
                lEDDataSet.Merge(m_data.LEDDatas);
                #region========LEDStatus==========
                LoadStatusData();
                foreach (DataRow dwTemp in LEDStatus.Rows)
                {
                    dwLEDStatus = dwTemp;
                }

                if (dwLEDStatus == null)
                {
                    foreach (DataRow dwTemp in lEDDataSet.LEDSTATUS.Rows)
                    {
                        string keyx = dwTemp["STSYSTEM"].ToString() + dwTemp["STLEDID"].ToString().Trim();
                        if (keyx == ledkey)
                        {
                            dwLEDStatus = dwTemp;
                        }
                    }
                }
                if (dwLEDStatus == null)
                {
                    dwLEDStatus = LEDStatus.Rows.Add();
                    dwLEDStatus["STSYSTEM"] = RowLED["LLSYSTEM"].ToString();
                    dwLEDStatus["STLEDID"] = RowLED["LLLEDID"].ToString();
                    dwLEDStatus["STPOWER"] = "0";
                    dwLEDStatus["STCURRENTTIME"] = DateTime.Now.ToFileTime();
                    dwLEDStatus["STRUN"] = "0";
                    dwLEDStatus["STBRIGHT"] = 7;
                    dwLEDStatus["STBGBMP"] = "NO";
                    dwLEDStatus["STFREESPACE"] = 204800;
                }
                BackGroundBmp = dwLEDStatus["STBGBMP"].ToString();
                #endregion
                GetDeviceParam(ref sender.devParam);
                sender.notifyMode = NOTIFY_BLOCK;
                sender.wmHandle = (UInt32)Hwnd;
                sender.wmMessage = (UInt32)WM_LED_NOTIFY;
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
        protected override void OnSourceInitialized(EventArgs e)
        {
            base.OnSourceInitialized(e);
            HwndSource source = PresentationSource.FromVisual(this) as HwndSource;
            source.AddHook(WndProc);//add hook to get message  
            Hwnd = source.Handle;
        }
        private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
        {
            IntPtr result = IntPtr.Zero;
            int paramx = wParam.ToInt32();
            string content = "";
            switch (msg)
            {
                case LEDAPI.WM_CREATE:
                    break;
                case LEDAPI.WM_LED_NOTIFY:
                    #region====WM_LED_NOTIFY====
                    PNotifyMessage Notify = new PNotifyMessage();
                    //if (LED_GetNotifyMessage(ref Notify) != 0)
                    {
                        switch (Notify.Message)
                        {
                            case LEDAPI.LM_TX_COMPLETE:
                                content = "发送完成";
                                dwLEDStatus["STSTATUS"] = "1";
                                break;
                            case LEDAPI.LM_RESPOND:
                                switch (Notify.Command)
                                {
                                    case LEDAPI.PKC_QUERY:
                                        content = "查询状态成功";
                                        dwLEDStatus["STSTATUS"] = "1";
                                        break;
                                    case LEDAPI.PKC_GET_POWER:
                                        content = (Notify.Status == LEDAPI.LED_POWER_ON) ? "电源已打开" : "电源已关闭";
                                        dwLEDStatus["STPOWER"] = Notify.Status;
                                        break;
                                    case LEDAPI.PKC_SET_POWER:
                                        if (Notify.Result == 99)
                                            content = "处于自动开关屏模式,不能进行电源操作!";
                                        else if (Notify.Status == LEDAPI.LED_POWER_ON)
                                        {
                                            dwLEDStatus["STPOWER"] = "1";
                                            content = "电源已打开";
                                        }
                                        else if (Notify.Status == LEDAPI.LED_POWER_OFF)
                                        {
                                            dwLEDStatus["STPOWER"] = "0";
                                            content = "电源已关闭";
                                        }
                                        break;
                                    case LEDAPI.PKC_GET_BRIGHT:
                                        content = "显示屏亮度为:" + Notify.Status;
                                        dwLEDStatus["STBRIGHT"] = Notify.Status;
                                        break;
                                    case LEDAPI.PKC_SET_BRIGHT:
                                        content = "亮度调整完毕";
                                        dwLEDStatus["STSETBRIGHT"] = "1";
                                        break;
                                    case LEDAPI.PKC_ADJUST_TIME:
                                        content = "时钟校正完成";
                                        dwLEDStatus["STSETCLOCK"] = "1";
                                        break;
                                }
                                break;
                            case LEDAPI.LM_TIMEOUT:
                                content = "传送超时";
                                break;
                        }
                    }
                    #endregion
                    DumpStatusData();
                    break;
                default:
                    break;
            }
            return result;
        }
        private void GetDeviceParam(ref TDeviceParam devp)
        {
            #region=======RowLED=============
            ledkey = RowLED["LLSYSTEM"].ToString() + RowLED["LLLEDID"].ToString().Trim();
            system = RowLED["LLSYSTEM"].ToString();
            ledid = System.Convert.ToInt16(RowLED["LLLEDID"].ToString().Trim());
            switch (RowLED["COMSPEED"].ToString().Trim())
            {
                case "SBR_57600":
                    comSpeed = SBR_57600;
                    break;
                case "SBR_19200":
                    comSpeed = SBR_19200;
                    break;
                case "SBR_9600":
                    comSpeed = SBR_9600;
                    break;
                case "SBR_38400":
                    comSpeed = SBR_38400;
                    break;
            }
            string sctype = RowLED["LLSCREENTYPE"].ToString();
            switch (sctype)
            {
                case "SCREEN_UNICOLOR":
                    screentyp = LEDAPI.SCREEN_UNICOLOR;
                    break;
                case "SCREEN_COLOR":
                    screentyp = LEDAPI.SCREEN_COLOR;
                    break;
                case "SCREEN_FULLCOLOR":
                    screentyp = LEDAPI.SCREEN_FULLCOLOR;
                    break;
                case "SCREEN_GRAY":
                    screentyp = LEDAPI.SCREEN_GRAY;
                    break;
                default:
                    screentyp = LEDAPI.SCREEN_COLOR;
                    break;
            }
            string DEVTYPE = RowLED["DEVTYPE"].ToString().Trim();
            switch (DEVTYPE)
            {
                case "DEVICE_TYPE_COM":
                    devType = LEDAPI.DEVICE_TYPE_COM;
                    break;
                case "DEVICE_TYPE_UDP":
                    devType = LEDAPI.DEVICE_TYPE_UDP;
                    break;
                case "DEVICE_TYPE_485":
                    devType = LEDAPI.DEVICE_TYPE_485;
                    break;
            }
            #endregion

            devp.devType=devType;
            devp.comSpeed = comSpeed;
            devp.comPort = System.Convert.ToUInt16(RowLED["COMPORT"].ToString());
            devp.comFlow = System.Convert.ToUInt16(RowLED["COMFLOW"].ToString());
            devp.locPort = System.Convert.ToUInt16(RowLED["LOCPORT"].ToString());
            devp.rmtPort = System.Convert.ToUInt16(RowLED["RMTPORT"].ToString());
            devp.srcAddr = System.Convert.ToUInt16(RowLED["SRCADDR"].ToString());
            devp.dstAddr = System.Convert.ToUInt16(RowLED["DSTADDR"].ToString());
            devp.rmtHost = System.Convert.ToString(RowLED["RMTHOST"].ToString());   
            devp.txTimeo = System.Convert.ToUInt32(RowLED["TXTIMEO"].ToString());
            devp.txRepeat =  System.Convert.ToUInt32(RowLED["TXREPEAT"].ToString());
            devp.txMovewin =  System.Convert.ToUInt32(RowLED["TXMOVEWIN"].ToString());
            devp.key = System.Convert.ToUInt32(RowLED["KEY"].ToString());
            devp.pkpLength =  System.Convert.ToInt32(RowLED["PKPLENGTH"].ToString());   				

        }
        private void LoadStatusData()
        {

            filepath = fileroot + @"\LED" + ledkey + @"\LEDStatus.XML";
            if (System.IO.File.Exists(filepath))
            {
                DataSet setResult = new DataSet();
                setResult.ReadXml(filepath);
                setLED = new DataSet();
                setLED.Merge(setResult);
                LEDStatus = setLED.Tables["LEDStatus"];
            }
        }
        public void DumpStatusData()
        {
            try
            {
                filepath = fileroot + @"\LED" + ledkey;
                if (!System.IO.Directory.Exists(filepath))
                {
                    System.IO.Directory.CreateDirectory(filepath);
                }
                filepath = fileroot + @"\LED" + ledkey + @"\LEDStatus.XML";
                if (System.IO.File.Exists(filepath))
                {
                    System.IO.File.Delete(filepath);
                    LEDStatus.WriteXml(filepath);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.StackTrace, ex.Message);
                Tracer.Error(ex.StackTrace, ex);
            }
        }
         
    }
}
